package com.ocm.commerceinteraction;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTabHost;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.ValueCallback;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.Toast;

import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.CmdMessageBody;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.google.gson.JsonSyntaxException;
import com.ocm.commerceinteraction.config.RequestAddr;
import com.ocm.commerceinteraction.model.BaseModel;
import com.ocm.commerceinteraction.model.FriendsList;
import com.ocm.commerceinteraction.model.UserModel;
import com.ocm.commerceinteraction.ui.AdvantureFragment_;
import com.ocm.commerceinteraction.ui.CenterFragment_;
import com.ocm.commerceinteraction.ui.CenterFragment_v2;
import com.ocm.commerceinteraction.ui.GoodFriendsFragment;
import com.ocm.commerceinteraction.ui.GoodFriendsFragment_;
import com.ocm.commerceinteraction.ui.HomeFragment;
import com.ocm.commerceinteraction.ui.HomeFragment_;
import com.ocm.commerceinteraction.ui.adapter.XTContactAdapter;
import com.ocm.commerceinteraction.util.MethedUtil;
import com.ocm.commerceinteraction.util.helper.DBHelper;
import com.ocm.commerceinteraction.util.helper.LogHelper;
import com.ocm.commerceinteraction.util.helper.NotifyUtil;
import com.ocm.commerceinteraction.util.http.AjaxCallBack;
import com.ocm.commerceinteraction.util.loading.Loading;
import com.readystatesoftware.systembartint.SystemBarTintManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import easeui.EaseConstant;
import easeui.controller.EaseUI;
import easeui.domain.EaseUser;
import easeui.utils.EaseCommonUtils;

import static com.easemob.EMNotifierEvent.Event.EventNewMessage;
import static com.ocm.commerceinteraction.GlobalApplication.*;

public class MainActivity extends FragmentActivity {

    private static MainActivity mainActivity;
    private static FragmentManager fragmentManager;
    public LayoutInflater layoutInflater;
    public ValueCallback<Uri> mUploadMessage;
    public final static int FILECHOOSER_RESULTCODE = 1;

    //定义数组来存放Fragment界面
    private Class fragmentArray[] = {HomeFragment_.class, GoodFriendsFragment_.class,
            AdvantureFragment_.class, CenterFragment_.class};

    //定义数组来存放按钮图片
    private int mImageViewArray[] = {R.drawable.tab_1_btn, R.drawable.tab_2_btn, R.drawable.tab_3_btn,
            R.drawable.tab_4_btn};


    //Tab选项卡的文字
    private String mTextviewArray[] = {"首页", "好友", "格子广告", "我的"};

    public static MainActivity getInstance() {
        return mainActivity;
    }

    public static FragmentManager getFragmentMangerinstance() {
        return fragmentManager;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        loadData();

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
//        GlobalData.screenWidth = dm.widthPixels;
//        GlobalData.screenHeight = dm.heightPixels;
        // 透明状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            // Translucent status bar
            window.setFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
//        //透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        setTranslucentStatus();
        mainActivity = this;
        Loading.mContext = this;
        fragmentManager = getSupportFragmentManager();
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); // 解决键盘顶tab问题
        fragmentManager = getSupportFragmentManager();
        layoutInflater = LayoutInflater.from(this);


        intiTab();
        tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
            @Override
            public void onTabChanged(String tabId) {

            }
        });

    }

    /**
     * 设置状态栏背景状态
     */
    private void setTranslucentStatus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window win = getWindow();
            WindowManager.LayoutParams winParams = win.getAttributes();
            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            winParams.flags |= bits;
            win.setAttributes(winParams);
        }

        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        // enable status bar tint
        tintManager.setStatusBarTintEnabled(true);
        // enable navigation bar tint
        tintManager.setNavigationBarTintEnabled(true);
        // set a custom tint color for all system bars
        tintManager.setTintColor(Color.parseColor("#2ed5bc"));
    }

    public FragmentTabHost tabHost;

    private void intiTab() {
        tabHost = (FragmentTabHost) findViewById(R.id.tab);
        tabHost.setup(this, getSupportFragmentManager(), R.id.content);
        int count = fragmentArray.length;
        for (int i = 0; i < count; i++) {
            TabHost.TabSpec tabSpec = tabHost.newTabSpec(mTextviewArray[i]).setIndicator(getTabItemView(i));
            tabHost.addTab(tabSpec, fragmentArray[i], null);
        }
        tabHost.getTabWidget().setDividerDrawable(null);
    }

    /**
     * 给Tab按钮设置图标和文字
     */
    private ImageView imageview;

    private View getTabItemView(int index) {
        View view = layoutInflater.inflate(R.layout.tab_item_view, null);
        imageview = (ImageView) view.findViewById(R.id.imageview);
        imageview.setImageResource(mImageViewArray[index]);
        return view;
    }

    private boolean is2CallBack = false;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (fragmentManager.getBackStackEntryCount() != 0) {
                    fragmentManager.popBackStack();
            } else {
                if (!is2CallBack) {
                    is2CallBack = true;
                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            is2CallBack = false;
                        }
                    }, 1500);
                } else {
                    android.os.Process.killProcess(android.os.Process.myPid());
                }
            }
        }
        return true;
    }

    /**
     * @param from       当前fragment
     * @param toFragment 跳转到的fragment
     */
    public static void switchFragment(Fragment from, Fragment toFragment) {
        if (toFragment.isAdded())
            return;
        getInstance().getSupportFragmentManager()
                .beginTransaction()
                .hide(from).replace(R.id.content_none_bottom, toFragment).addToBackStack(null).commit();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //注册新消息监听
//        IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
//        intentFilter.setPriority(3);
//        GlobalApplication.getInstance().registerReceiver(msgReceiver, intentFilter);
//        EMChat.getInstance().setAppInited();
        if (tabHost.getCurrentTab() == 1) {
            tabHost.setCurrentTab(1);
        }


//        NewMessageBroadcastReceiver msgReceiver = new NewMessageBroadcastReceiver();
//        IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
//        intentFilter.setPriority(3);
//        GlobalApplication.getInstance().registerReceiver(msgReceiver, intentFilter);
        //注：回调 1
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //注：回调 2
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        //注：回调 3
        return super.dispatchTouchEvent(event);
    }

    private void loadData() {
        String requestUrl = RequestAddr.serarchFriList;
        GlobalApplication.xtHttp.get(requestUrl, new AjaxCallBack<Object>() {

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                dealData(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }


    //处理数据
    BaseModel baseModel;
    FriendsList friendsList;
    List<UserModel> userModelList = new ArrayList<>();
    XTContactAdapter xtContactAdapter;
    private void dealData(Object object) {
        try {
            friendsList = GlobalApplication.gson.fromJson(object.toString(), FriendsList.class);
        } catch (JsonSyntaxException e) {
            baseModel = GlobalApplication.gson.fromJson(object.toString(), BaseModel.class);
            return;
        }

//        DBHelper.removeMoveFriendList();
        DBHelper.addFriendList(friendsList);
    }

}
